package com.yunliuchain.examination.common.web.controller.admin;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.yunliuchain.examination.common.bean.FileMeta;
import com.yunliuchain.examination.common.config.YunBanDanProperties;
import com.yunliuchain.examination.common.res.ApiResult;
import com.yunliuchain.examination.common.service.FileUploadService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * @author 朱周城
 * @version 1.0
 * @date 2014年5月29日上午10:14:33
 */
@RequestMapping("/yunbandan/admin/common/fileUpload")
@Controller
@Api(description = "文件上传接口")
public class FileUploadAdminController
{

	@Autowired
	private FileUploadService fileUploadService;

	@Autowired
	private YunBanDanProperties yhgProperties;


	@RequestMapping(value="/upload",method=RequestMethod.POST)
	public void upload(HttpServletRequest request, HttpServletResponse response) throws IOException{
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		try
		{
			List<FileMeta> list = fileUploadService.upload(request);
			Iterator<FileMeta> it = list.iterator();
			if(it.hasNext()){
				while(it.hasNext()){
					FileMeta f = it.next();
					if(f != null){
						out.println(getMessage(0,f.getUrl()));
						out.flush();
					}
				}
			}else {
				out.println(getMessage(-1,"没有文件"));
			}


		}catch(Exception e){
			e.printStackTrace();
			out.println(getMessage(-1,e.getMessage()));
			out.flush();
		}finally{
			if (out != null)
			{
				out.close();
			}
		}
	}

//	@ResponseBody
//	@RequestMapping(value="/deleteUploadFile")
//	public boolean deleteFile(HttpServletRequest request, HttpServletResponse response, String filePath) throws IOException{
//		return fileUploadService.deleteUploadFile(request, filePath);
//	}

	private String getMessage(int code, String result) {
		if(code == 0){
			Map map = new HashMap();
			map.put("url",result);
			map.put("fullUrl",yhgProperties.getAppPicUrl() + result);
			return JSON.toJSONString(ApiResult.success(map));
		}else {
			return  JSONObject.toJSONString(ApiResult.fail(result)) ;
		}
	}

//	@RequestMapping("/manager")
//	public void manager(HttpServletRequest request, HttpServletResponse response){
//		PrintWriter out  = null;
//		try
//		{
//			out =  response.getWriter();
//			String rootPath = yhgProperties.getUploadPath();
//			//根目录路径，可以指定绝对路径，比如 /var/www/attached/
//			String rootUrl  = yhgProperties.getUploadUrl();
//			String dirTypeName = request.getParameter("dirType");
//			String dirName = request.getParameter("dir");
//			if (dirTypeName == null) {
//				dirTypeName = "defDir";
//			}
//			if (dirName != null) {
//				if(!Arrays.<String>asList(new String[]{"image", "flash", "media", "file","product","adv"}).contains(dirName)){
//					out.println("Invalid Directory name.");
//					return;
//				}
//				rootPath += "/"+dirTypeName + "/"+dirName + "/";
//				rootUrl += "/"+dirTypeName + "/"+dirName + "/";
//				File saveDirFile = new File(rootPath);
//				if (!saveDirFile.exists()) {
//					saveDirFile.mkdirs();
//				}
//			}
//			//根据path参数，设置各路径和URL
//			String path = request.getParameter("path") != null ? request.getParameter("path") : "";
//			String currentPath = rootPath + path;
//			String currentUrl = rootUrl + path;
//			String currentDirPath = path;
//			String moveupDirPath = "";
//			if (!"".equals(path)) {
//				String str = currentDirPath.substring(0, currentDirPath.length() - 1);
//				moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : "";
//			}
//
//			//排序形式，name or size or type
//			String Order = request.getParameter("Order") != null ? request.getParameter("Order").toLowerCase() : "name";
//
//			//不允许使用..移动到上一级目录
//			if (path.indexOf("..") >= 0) {
//				out.println("Access is not allowed.");
//				return;
//			}
//			//最后一个字符不是/
//			if (!"".equals(path) && !path.endsWith("/")) {
//				out.println("Parameter is not valid.");
//				return;
//			}
//			//目录不存在或不是目录
//			File currentPathFile = new File(currentPath);
//			if(!currentPathFile.isDirectory()){
//				out.println("Directory does not exist.");
//				return;
//			}
//
//			//遍历目录取的文件信息
//			List<Map<String,Object>> fileList = fileUploadService.getFileList(currentPathFile);
//			fileUploadService.sortFile(fileList, Order);
//			JSONObject result = new JSONObject();
//			result.put("moveup_dir_path", moveupDirPath);
//			result.put("current_dir_path", currentDirPath);
//			result.put("current_url", currentUrl);
//			result.put("total_count", fileList.size());
//			result.put("file_list", fileList);
//			response.setContentType("application/json; charset=UTF-8");
//			out.println(result.toString());
//			out.flush();
//		} catch (Exception e)
//		{
//			e.printStackTrace();
//		}finally{
//			if (out != null)
//			{
//				out.close();
//			}
//		}
//	}
	
	 
}
